﻿/*
cd /projects/hsieh_project/proj_201809/code_1_data/
qsas ec_1_lbd_merge.sas 8 &
*/

libname llbd "/projects/data_commons/lbd/";
libname lec "/projects/flin/data_clean/ec/";
libname leca "/projects/data_p/build/mst/";

%Let dir_llbd=/projects/data_commons/lbd/;
%Let dir_lec=/projects/flin/data_clean/ec/;
%Let dir_leca=/projects/data_p/build/mst/;

libname ldcec "/projects/data_commons/ec/";
%Let dir_ldcec=/projects/data_commons/ec/;

/*
--------------------------------------------------------------------------------
*/

%macro m_ec_merge();

proc import out=dt_ec datafile="&dir_leca./01b_unique_EC_appended_v12.dta";
run;

data dt_ec;
  set dt_ec;
  if year in (1977,1982,1987,1992,1997,2002,2007,2012);
  rename lbdid_v16=lbdid final_sales=sales;
run;

proc sort data=dt_lbd; by year lbdid;
proc sort data=dt_ec; by year lbdid;

data dt_merge;
  merge dt_ec (in=x) dt_lbd (in=y);
  by year lbdid;
  if x then in_ec=1;
  if y then in_lbd=1;
run;

data dt_merge;
  set dt_merge(rename=year=year1);
  est = 1;
  year=year1; /* Rename to lower case */
  drop year1;
  if firmnum ~= . then w_firmnum = 1;
run;

proc sort data=dt_merge; by year in_ec in_lbd w_firmnum;

proc means data=dt_merge noprint;
  by year in_ec in_lbd w_firmnum;
  output out=dt_out sum(worker est salary sales)=worker est salary sales;
run;

%mend;

/*
----------------------------------------
Use cleaned lbd
*/

data dt_lbd;
  set llbd.lbd_clean;
  if year in (1977,1982,1987,1992,1997,2002,2007,2012);
run;

%m_ec_merge();

data lec.ec_lbd_clean_merge;
  set dt_merge;
run;

data ldcec.ec_lbd_clean_merge;
  set dt_merge;
run;

/*
----------------------------------------
Use very raw lbd
*/

data dt_lbd;
  set llbd.lbd_raw_orig;
  if yr in (1977,1982,1987,1992,1997,2002,2007,2012);
  rename yr=year;
run;

%m_ec_merge();

proc export data=dt_out outfile="&dir_lec./ec_lbd_raw_merge_sum.dta" replace;
run;

/* End of sas file */
